package com.yzyz.management.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.yzyz.bean.route.RouteBean;
import com.yzyz.service.IRouteService;
import com.yzyz.utils.CommonHandle;
import com.yzyz.utils.ValidateUtils;
import com.yzyz.utils.error.ErrorBean;
import com.yzyz.utils.error.Error;
import com.yzyz.utils.json.management.JSONRouteM;



/**
 * To manage all routes
 * @author David Sun
 * @Date   2010-3-13
 *
 */
public class RouteController extends MultiActionController {
	Log logger = LogFactory.getLog(RouteController.class);
	private IRouteService routeService;
	public void setRouteService(IRouteService routeService) {
		this.routeService = routeService;
	}
	public void getRoutes(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int start = Integer.valueOf(request.getParameter("start"));
		int limit = Integer.valueOf(request.getParameter("limit"));
		int groupId = -1;
		if(!ValidateUtils.isNull(request.getParameter("groupId"))) {
			groupId = Integer.valueOf(request.getParameter("groupId"));
		}
		List<RouteBean> routes = this.routeService.listAll(start, limit, request.getParameter("routeName"), groupId);
		List<JSONRouteM> js = new ArrayList<JSONRouteM>();
		if(routes != null) {
			for(RouteBean route: routes) {
				JSONRouteM  r = new JSONRouteM(route);
				js.add(r);
			}
		}
		JSONArray arr = JSONArray.fromObject(js, JSONRouteM.getConfig());
		StringBuffer sb 			= new StringBuffer();
		sb.append("{\"sum\":").append("\""+this.routeService.getCountOfAll(request.getParameter("routeName"), groupId)+"\",");
		sb.append("\"data\":").append(arr.toString());
		sb.append("}");
		this.writeToClient(response, sb.toString());
		
	}
	public void getContents(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int id = Integer.valueOf(request.getParameter("routeId"));
		RouteBean route = (RouteBean)this.routeService.find(id);
		ErrorBean error = ErrorBean.getInstance(Error.SUCCESS, route.getContents());
		this.writeToClient(response, error.toJson());
	}
	public void addRoute(HttpServletRequest request, HttpServletResponse response) throws IOException {
		int result = ValidateUtils.validateNewRoute(request);
		if(result != Error.SUCCESS) {
			ErrorBean error = ErrorBean.getInstance(result, Error.errorMsg[result]);
			this.writeToClient(response, error.toJson());
			return;
		}
		RouteBean route = this.getNewForm(request);
		this.routeService.add(route);
		ErrorBean error = ErrorBean.getInstance(Error.SUCCESS, String.valueOf(route.getId()));
		this.writeToClient(response, error.toJson());

	}
	public void update(HttpServletRequest request, HttpServletResponse response) throws IOException{
		int result = ValidateUtils.validateEditRoute(request);
		if(result != Error.SUCCESS) {
			ErrorBean error = ErrorBean.getInstance(result, Error.errorMsg[result]);
			this.writeToClient(response, error.toJson());
			return;
		}
		if(ValidateUtils.isNull(request.getParameter("routeId"))) {
			logger.warn(CommonHandle.now() + " The routeId is null.");
			ErrorBean error = ErrorBean.getInstance(Error.ROUTE_ID_REQUIRED, Error.errorMsg[Error.ROUTE_ID_REQUIRED]);
			this.writeToClient(response, error.toJson());
			return;
		}
		result = this.routeService.update(this.getEditForm(request));
		if(result != Error.SUCCESS) {
			ErrorBean error = ErrorBean.getInstance(result, Error.errorMsg[result]);
			this.writeToClient(response, error.toJson());
			return;
		} else {
			ErrorBean error = ErrorBean.getInstance(result, "添加成功");
			this.writeToClient(response, error.toJson());
			return;
		}
	}
	public void disable(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(ValidateUtils.isNull(request.getParameter("routeId"))) {
			ErrorBean error = ErrorBean.getInstance(Error.ROUTE_ID_REQUIRED, Error.errorMsg[Error.ROUTE_ID_REQUIRED]);
			this.writeToClient(response, error.toJson());
			return;
		}
		int result = this.routeService.disable(Integer.valueOf(request.getParameter("routeId").trim()));
		if(result != Error.SUCCESS) {
			ErrorBean error = ErrorBean.getInstance(result, Error.errorMsg[result]);
			this.writeToClient(response, error.toJson());
			return;
		}
		
		ErrorBean error = ErrorBean.getInstance(result, "操作成功");
		this.writeToClient(response, error.toJson());
		return;
	}
	public void enable(HttpServletRequest request, HttpServletResponse response) throws IOException {
		if(ValidateUtils.isNull(request.getParameter("routeId"))) {
			ErrorBean error = ErrorBean.getInstance(Error.ROUTE_ID_REQUIRED, Error.errorMsg[Error.ROUTE_ID_REQUIRED]);
			this.writeToClient(response, error.toJson());
			return;
		}
		int result = this.routeService.enable(Integer.valueOf(request.getParameter("routeId").trim()));
		if(result != Error.SUCCESS) {
			ErrorBean error = ErrorBean.getInstance(result, Error.errorMsg[result]);
			this.writeToClient(response, error.toJson());
			return;
		}
		
		ErrorBean error = ErrorBean.getInstance(result, "操作成功");
		this.writeToClient(response, error.toJson());
		return;
	}
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException{
		if(ValidateUtils.isNull(request.getParameter("routeId"))) {
			ErrorBean error = ErrorBean.getInstance(Error.ROUTE_ID_REQUIRED, Error.errorMsg[Error.ROUTE_ID_REQUIRED]);
			this.writeToClient(response, error.toJson());
			return;
		}
		int result = this.routeService.delete(Integer.valueOf(request.getParameter("routeId").trim()));
		if(result != Error.SUCCESS) {
			ErrorBean error = ErrorBean.getInstance(result, Error.errorMsg[result]);
			this.writeToClient(response, error.toJson());
			return;
		}
		ErrorBean error = ErrorBean.getInstance(result, "删除成功");
		this.writeToClient(response, error.toJson());
		return;
	}
	
	/**
	 * 添加关联的景区
	 * @param request
	 * @param response
	 */
	public void addUsedScenic(HttpServletRequest request, HttpServletResponse response){
		
	};
	
	/**
	 * 取消已经关联的景区
	 * @param request
	 * @param response
	 */
	public void cancelUsedScenic(HttpServletRequest request, HttpServletResponse response){
		
	};
	private void writeToClient(HttpServletResponse response, String contents) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Programa", "no-cache");
		response.setDateHeader("Expires", -1L);
		response.setContentType("text/html; charset=UTF-8");
		response.getWriter().write(contents);
		response.flushBuffer();
		response.getWriter().close();
	}
	
	private RouteBean getEditForm(HttpServletRequest request){
		RouteBean route = new RouteBean();
		route.setContents(request.getParameter("contents"));
		route.setName(request.getParameter("name"));
		route.setPrice(request.getParameter("price"));
		route.setId(Integer.valueOf(request.getParameter("routeId")));
		route.setLevel(Integer.valueOf(request.getParameter("level")));
		route.setRouteGroupId(Integer.valueOf(request.getParameter("routeGroupId")));
		return route;
	}
	
	private RouteBean getNewForm(HttpServletRequest request) {
		String price 	= request.getParameter("price");
		String name 	= request.getParameter("name");
		String contents = request.getParameter("contents");
		RouteBean route = new RouteBean();
		route.setAvailable(true);
		route.setDate(new Date());
		route.setLevel(0);
		route.setName(name);
		route.setPrice(price);
		route.setContents(contents);
		route.setLevel(Integer.valueOf(request.getParameter("level")));
		route.setRouteGroupId(Integer.valueOf(request.getParameter("routeGroupId")));
		return route;
	}
}
